package com.asp.aspchain.account.controller;

import com.alibaba.fastjson.JSON;
import com.asp.aspchain.account.constants.ErrorCode;
import com.asp.aspchain.account.request.CrtAccountReq;
import com.asp.aspchain.core.model.AppBaseModel;
import com.asp.aspchain.core.service.IAppBaseService;
import com.asp.aspchain.core.util.AjaxResult;
import com.asp.aspchain.core.util.BlogUtil;
import com.asp.aspchain.core.util.CommonUtil;
import com.asp.aspchain.core.util.HttpRequestUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Iterator;
import java.util.Set;

@RestController
@RequestMapping("/account")
public class CrtAccountController {

	private final static Logger logger = Logger.getLogger(CrtAccountController.class);
	@Autowired
	private IAppBaseService appBaseService;
	@Value("${server.port}")
	private String port;
	@Value("${server.context-path}")
	private String context;
	@Autowired
	private Validator validator;

	@PostMapping("/crtaccount")
	public AjaxResult AccountHandler(@RequestBody String json) {

		logger.info("=============AccountHandler开始=============");
		logger.info(json);
		// 接受前端请求记录内部日志
		BlogUtil.inlog(json, "", "account/crtaccount/", "crtaccount", "req");
		CrtAccountReq accountReq = null;
		try {
			accountReq = JSON.parseObject(json, CrtAccountReq.class);
		} catch (Exception e) {
			logger.error("创建账户接口解析错误：" + e.getMessage());
			e.printStackTrace();
		}

		// 参数校验
		AjaxResult result = checkPayParam(accountReq);
		if (result != null) {
			return result;
		}
		
		// 验证签名
		if (!sign(accountReq.getHmac())) {
			return new AjaxResult(ErrorCode.SIGN_ERROR, "签名验证失败", "签名验证失败");
		}

		// 生成url
		InetAddress addr = null;
		try {
			addr = InetAddress.getLocalHost();
		} catch (UnknownHostException e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}

		String ip = "localhost:" + port;
		String url = null;
		AppBaseModel appBaseModel = appBaseService.selectOne(new EntityWrapper<AppBaseModel>().eq("appmark", accountReq.getAppmark()));
		String tokenType = appBaseModel.getTokentype();
		String accountType = appBaseModel.getAccounttype();
		String eoa = "00";
		String coa = "01";
		if (eoa.equals(accountType)) {
			url = "http://" + ip + context + "/account/eoa/crtaccount";
		} else if (coa.equals(accountType)) {
			url = "http://" + ip + context + "/account/coa/" + tokenType + "/crtaccount";
		}
		// 发送请求
		String resp = HttpRequestUtil.postJson(url, json);
		AjaxResult ajaxResult = JSON.parseObject(resp, AjaxResult.class);
		BlogUtil.inlog(resp, "", "account/crtaccount/", "crtaccount", "resp");
		logger.info("=============AccountHandler结束=============");
		return ajaxResult;
	}

	private AjaxResult checkPayParam(CrtAccountReq accountReq) {
		// 参数校验
		Set<ConstraintViolation<CrtAccountReq>> validate = validator.validate(accountReq);
		if (validate.size() > 0) {
			// 如果有错误，取出一条信息返回
			String message = validate.iterator().next().getMessage();
			return new AjaxResult(ErrorCode.PARAM_ERROR, message, message);
		}
		
		String appmark = accountReq.getAppmark();
		String tokentype = accountReq.getTokentype();
		String idetification  = accountReq.getIdentification();
		AppBaseModel appBaseModel = appBaseService.selectOne(new EntityWrapper<AppBaseModel>().eq("appmark", appmark));
		if (appBaseModel == null) {
			return new AjaxResult(ErrorCode.APP_NOT_EXIST, "不存在该app", "不存在该app");
		}
		if (StringUtils.isNotBlank(tokentype)) {
			if (!tokentype.equals(appBaseModel.getTokentype())) {
				return new AjaxResult(ErrorCode.TOKENTYPE_ERROR, "tokentype与配置信息不一致", "tokentype与配置信息不一致");
			}
		}
		//type=1即身份证
		String type = "1";
		if(type.equals(accountReq.getIdtype())){
			if(!CommonUtil.isValidatedAllIdcard(idetification)){
				return new AjaxResult(ErrorCode.IDNO_ILLEGAL,"身份证不合法","身份证不合法");
			}
		}

		return null;
	}

	private boolean sign(String hmac) {
		// TODO Auto-generated method stub
		return true;
	}

	private static Validator validato2r = Validation.buildDefaultValidatorFactory().getValidator();

	public static void main(String[] args) {
		CrtAccountReq accountReq = new CrtAccountReq();
		accountReq.setIdtype("33");
		accountReq.setTokenvalue(20);
		accountReq.setPassword("12345678912345678");
		accountReq.setTokentype("sssss");
		Set<ConstraintViolation<CrtAccountReq>> validate = validato2r.validate(accountReq);
		Iterator<ConstraintViolation<CrtAccountReq>> iterator = validate.iterator();
		while (iterator.hasNext()) {
			String message = iterator.next().getMessage();
			System.out.println(message);
		}

	}
}
